<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/8/11
 * Time: 18:23
 */

namespace App\Service;


use App\Models\Permission;
use Illuminate\Support\Facades\DB;

class PermissionService
{
    /**
     * 获取权限列表
     * @param array $params
     * @param string $orderBy
     * @param string $sort
     * @return \Illuminate\Http\JsonResponse
     */
    public static function getList($params = [],$orderBy = 'order',$sort = 'ASC')
    {
        $where = [];
//        $permissionModel = new Permission();
        if(isset($params['name']) && empty($params['name'])){
            $where[] = ['name','like',"%{$params['name']}%"];
        }
        $list = Permission::where($where)->orderBy($orderBy,$sort)->get(['id','name','slug','parent_id','order','created_at','updated_at'])->toArray();
        $list = getTree($list);
        return Response()->json(['code'=>200,'msg'=>'获取成功','data'=>$list]);
    }

    /**
     * 通过ID获取权限
     * @param int $permissionId
     * @return array
     */
    public static function getPermissionById($permissionId = 0)
    {
        $info = Permission::where('id', $permissionId)->first(['id','name','slug','parent_id','order','created_at','updated_at']);
        $info = $info ? $info->toArray() : [];
        return Response()->json(['code' => 200, 'msg' => '获取成功', 'data' => $info]);

    }

    /**
     * 添加
     * @param array $params
     * @return \Illuminate\Http\JsonResponse
     */
    public static function add($params = [])
    {
        try{
            if(Permission::where('slug',trim($params['slug']))->first()){
                throw new \Exception('该权限标识已存在');
            }
            $info = Permission::create(['parent_id'=>intval($params['parent_id']),'name'=>trim($params['name']),'slug'=>trim($params['slug']) ,'order'=>intval($params['order'])]);
            if(!$info){
                throw new \Exception('新增失败');
            }

        }catch (\Exception $e){
            return Response()->json(['code'=>201,'msg'=>$e->getMessage()]);
        }
        return Response()->json(['code'=>200,'msg'=>'新增成功']);


    }

    /**
     * 修改
     * @param array $params
     * @return \Illuminate\Http\JsonResponse
     */
    public static function edit($params = [])
    {
        try{
            $info = Permission::where('id',intval($params['id']))->first();
            if(!$info){
                throw new \Exception('该权限不存在');
            }
            if(Permission::where('slug',trim($params['slug']))->where('id','!=',intval($params['id']))->first()){
                throw new \Exception('该权限标识已存在');
            }
            $info->name = trim($params['name']);
            $info->slug = trim($params['slug']);
            $info->parent_id = intval($params['parent_id']);
            $info->order = intval($params['order']);
            $save = $info->save();
            if(!$save) throw new \Exception('修改失败');
        }catch (\Exception $e){
            return Response()->json(['code'=>201,'msg'=>$e->getMessage()]);
        }
        return Response()->json(['code'=>200,'msg'=>'修改成功']);
    }

    /**
     * 删除
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public static function destroy($id)
    {
        $idArr = is_array($id) ? $id : [$id];
        if(!$idArr){
            return Response()->json(['code'=>201,'msg'=>'请选择要删除的权限']);
        }
        $del = Permission::destroy($idArr);
        if(!$del){
            return Response()->json(['code'=>201,'msg'=>'删除失败']);
        }
        $list  = Permission::orderBy('order','DESC')->get(['id', 'parent_id', 'order', 'name','slug'])->toArray();
        $sonArr = [];
        foreach($idArr as $v){
            $sonList = getSubs($v,$list);
            if($sonList){
                $sonArr = array_merge(array_column($sonList,'id'),$sonArr) ;
            }
        }
        if($sonArr){
            Permission::destroy($sonArr);
        }
        DB::table('admin_role_permissions')->whereIn('permission_id',array_merge($sonArr,$idArr))->delete();
        return Response()->json(['code'=>200,'msg'=>'删除成功']);

    }

}
